

package com.kimo.shop.user.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kimo.shop.bean.param.ScoreExpireParam;
import com.kimo.shop.common.annotation.SysLog;
import com.kimo.shop.common.bean.SysConfig;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.util.Json;
import com.kimo.shop.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;


/**
 * 积分过期配置
 * @author kimo-taozhouchuan
 */
@RestController
@RequestMapping("/user/scoreExpire")
public class ScoreExpireConfigController {

	@Autowired
	private SysConfigService sysConfigService;


	/**
	 * 配置信息
	 */
	@GetMapping("/info/{id}")
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:info')")
	public ResponseEntity<ScoreExpireParam> info(@PathVariable("id") String key){
		SysConfig config = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getParamKey,key));
		if(Objects.isNull(config)){
			return ResponseEntity.ok().build();
		}
		ScoreExpireParam expireParam = Json.parseObject(config.getParamValue(), ScoreExpireParam.class);
		return ResponseEntity.ok(expireParam);
	}

	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('user:GrowthConfig:save')")
	public ResponseEntity<Void> save(@RequestBody @Valid ScoreExpireParam expireParam){
		SysConfig config = new SysConfig();

		String paramValue = Json.toJsonString(expireParam);
		config.setParamKey(Constant.SCORE_EXPIRE);
		config.setParamValue(paramValue);
		config.setRemark("积分过期规则");
		if (sysConfigService.count(new LambdaQueryWrapper<SysConfig>()
				.eq(SysConfig::getParamKey, config.getParamKey())) > 0) {
			sysConfigService.update(new LambdaUpdateWrapper<SysConfig>()
					.set(SysConfig::getParamValue,config.getParamValue())
					.set(SysConfig::getRemark,config.getRemark())
					.eq(SysConfig::getParamKey,config.getParamKey()));
		}else {
			sysConfigService.save(config);
		}
		sysConfigService.removeSysConfig(Constant.SCORE_EXPIRE);
		return ResponseEntity.ok().build();
	}


}
